<?php
/**
 * Created by PhpStorm.
 * User: liuhong
 * Date: 2019-04-09
 * Time: 16:01
 */

namespace app\service;


use app\model\AddressModel;
use think\Db;
use think\Exception;
use think\Model;

/**
 * 地址信息
 * Class AddressService
 * @package app\service
 */
class AddressService extends BaseService
{
    public $addressModel;
    public $expressModel;
    public function __construct()
    {
        $this->addressModel=new AddressModel();
        $this->expressModel=Db::name('express');
    }


    //查询收货地址详情
    public function findAddress($where,$filed=null){
        try{
           return $this->addressModel->field($filed)->where($where)->find()->toArray();
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }

    /*
    * 计算运费
    * TODO
    */
    public function _get_shipping($goods_info,$aid='浙江省'){
        try{
            $all_weight = 0;//订单总重量
            $where = array(
                "province_name" => $aid
            );
            $res = $this->expressModel->where($where)->find();
            //首重和续重
            $first = $res["first_weight"];
            $next = $res["next_weight"];
            foreach ($goods_info as $k=>$v){
                //判断是不是包邮商品
                if($v['freight_payer'] == 1){
                    continue;
                }
                $all_weight += $v['goods_num'] * $v['weight'];
            }
            $all_weight = ceil($all_weight);
            if($all_weight == 0){
                $money = 0;
            }else if($all_weight<=1){
                $money = $first;
            }else{
                $money = $first + ($all_weight-1)*$next;
            }
            $money = round($money,2);//四舍五入
            return $money;
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return 0;
        }

    }

    //查询收货地址详情
    public function selectAddress($uid){
        try{
            return $this->addressModel->where('uid',$uid)->order('is_default desc')->select()->toArray();
        }catch (Exception $ex){
            echo $ex->getMessage();
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }

    //删除收货地址
    public function delAddress($id,$uid){
       return $this->addressModel->where(array('id'=>$id,'uid'=>$uid))->delete();
    }


    /**新增
     * @param $add
     * @param null $id
     * @return false|int
     */
    public function add($add,$id=null){
        if($add['is_default']==1){
            $this->addressModel->save(array('is_default'=>0),array('uid'=>$add['uid']));
        }
        if(empty($id)){
            $add['create_time']=date('Y-m-d H:i:s');
            return $this->addressModel->insertGetId($add);
        }else{
            return $this->addressModel->save($add,array('id'=>$id));
        }
    }
}